import {OpenAIOutlined, UserOutlined} from '@ant-design/icons';
import {Attachments, Bubble} from '@ant-design/x';
import {Flex, GetProp} from 'antd';
import React from "react";
import markdownit from 'markdown-it';
import {BubbleContent, BubbleItem, FileContent} from "../types/CommonTypes";
import MsgOperate from "./MsgOperate.tsx";
import {BubbleDataType} from "@ant-design/x/es/bubble/BubbleList";


type RundelBubbleProp={
    items: BubbleItem[],
    defaultNode: BubbleDataType[]
}
const RundelBubble:React.FC<RundelBubbleProp> = ({items, defaultNode}) => {
    const fileMapping = React.useRef<Record<string, any>>({});
    const md = markdownit({html: true, breaks: true});
    const renderAiMarkdown = (content: any) => {
        const con = content as BubbleContent;
        const message = con.msg;
        const msgId = con.msgId;
        const inFiles = con.files;
        const msgKey = con.msgId + con.role;
        let cacheFiles = fileMapping.current[msgKey];
        if (!cacheFiles && inFiles) {
            fileMapping.current[msgKey] = inFiles;
            cacheFiles = inFiles;
        }
        const filesNode = buildFileNode(cacheFiles);
        return (
            <>
                <div dangerouslySetInnerHTML={{__html: md.render(message)}}/>
                <MsgOperate msgId={msgId} msg={message} opTypes={con.opTypes} role={con.role} />
                {filesNode}
            </>
        )
    }
    const buildFileNode = (files?: FileContent[]) =>{
        if (!files || !files.length) return "";
        return (
            <Flex vertical gap="middle">
                {(files).map((item) => (
                    <Attachments.FileCard key={item.fileId} item={{uid:item.fileId,...item}} />
                ))}
            </Flex>
        );
    }
    const roles: GetProp<typeof Bubble.List, 'roles'> = {
        ai: {
            placement: 'start',
            typing: {step: 5, interval: 20},
            styles: {
                content: {
                    borderRadius: 16,
                },
            },
            avatar:{ icon: <OpenAIOutlined/>, style: { background: '#fde3cf' } },
            messageRender: renderAiMarkdown,
        },
        local: {
            placement: 'end',
            variant: 'shadow',
            avatar: {icon: <UserOutlined/>, style: { visibility: 'visible' }},
            messageRender: renderAiMarkdown,
        },
    };
    return (
        <Bubble.List
            roles={roles}
            style={{flex:1}}
            items={items.length > 0 ? items : defaultNode}
        />
    );
};

export default RundelBubble;